package com.zhida.jiyangcenter.modle

import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.widget.AppCompatImageView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.utils.*
import chooongg.base.widget.recyclerView.divider.HorizontalDividerItemDecoration
import chooongg.base.widget.recyclerView.divider.VerticalDividerItemDecoration
import chooongg.http.APIException
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.api.APIAccount
import com.zhida.jiyangcenter.api.APIShop
import com.zhida.jiyangcenter.api.BaseAPI
import com.zhida.jiyangcenter.api.ShopInfoEntity
import com.zhida.jiyangcenter.buycar.ShopCarActivity
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.order.ConfirmOrderActivity
import com.zhida.jiyangcenter.utils.glideImage
import com.zhida.jiyangcenter.utils.request
import com.zhida.jiyangcenter.widget.ResizableImageView
import kotlinx.android.synthetic.main.activity_physical_examination.*
import kotlinx.android.synthetic.main.activity_shop_details.*
import kotlinx.android.synthetic.main.activity_shop_details.appbar_layout
import kotlinx.android.synthetic.main.activity_shop_details.title_bar
import me.zhanghai.android.materialratingbar.MaterialRatingBar
import java.math.RoundingMode

@TitleBar(false)
@ContentLayout(R.layout.activity_shop_details)
class ShopDetailsActivity : BaseActivity() {
    private var statusBarIsLight = true
    val itemAdapter = ItemAdapter()
    val imageAdapter = ImageAdapter()
    override fun initConfig(savedInstanceState: Bundle?) {
        title_bar.navigationIcon(R.drawable.iv_back_fill) {
            finish()
        }
        title_bar.title("详情")
        rv_shop_details_tab.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        rv_shop_details_tab.addItemDecoration(
            VerticalDividerItemDecoration.Builder(context).sizeResId(R.dimen.dividerBig)
                .colorResId(R.color.white).build()
        )
        rv_shop_details_tab.adapter = itemAdapter
        ctl_shop_details.minimumHeight = getStatusBarHeight() + resDimenSize(R.dimen.titleBarHeight)
        tv_shop_details_mendian_more.setOnClickListener {
            startActivity<CommentListActivity> {
                putExtra("kind", "0")
                putExtra("uuid", intent.getStringExtra("uuid"))
            }
        }
        appbar_layout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
            val minHeight = -appbar_layout.height + ctl_shop_details.minimumHeight
            val percentage = Math.abs(verticalOffset).toFloat() / Math.abs(minHeight).toFloat()
            when {
                percentage in 0.4f..0.9f -> {
                    title_bar.alpha = ((percentage - 0.4f) / 0.5f)
                    bga_shop_details.alpha = 1f
                }
                percentage > 0.5f -> {
                    title_bar.alpha = 1f
                    bga_shop_details.alpha = 0f
                    if (statusBarIsLight) {
                        statusBarIsLight = false
                        setStatusBarLightMode(statusBarIsLight)
                    }
                }
                else -> {
                    title_bar.alpha = 0f
                    bga_shop_details.alpha = 1f
                    if (!statusBarIsLight) {
                        statusBarIsLight = true
                        setStatusBarLightMode(statusBarIsLight)
                    }
                }
            }
        })

        cl_shop_details_coupon.setOnClickListener {
            val bottomSheetDialog = BottomSheetDialog(context, R.style.BottomSheetDialog)
            val view = layoutInflater.inflate(R.layout.dialog_shop_details_coupon, null, false)
            val rv_dialog = view.findViewById<RecyclerView>(R.id.rv_shop_details)
            rv_dialog.addItemDecoration(
                HorizontalDividerItemDecoration.Builder(context)
                    .sizeResId(R.dimen.dividerBig).colorResId(R.color.colorBack).build()
            )
            rv_dialog.layoutManager = LinearLayoutManager(context)
            rv_dialog.adapter = DialogAdapter().apply {
                setNewData(ArrayList<String>().apply {
                    add("kasj")
                    add("kasj")
                    add("kasj")
                    add("kasj")
                    add("kasj")
                    add("kasj")
                    add("kasj")
                    add("kasj")
                    add("kasj")
                    add("kasj")
                    add("kasj")
                    add("kasj")
                    add("kasj")
                })
            }
            bottomSheetDialog.setContentView(view)
            bottomSheetDialog.show()
        }
        tv_shop_details_buy_car.setOnClickListener {
            startActivity<ShopCarActivity> { }
        }
        button_shop_details_buy_car.setOnClickListener {
            lifecycleScope.request({
                APIShop.service().shopcarAdd(intent.getStringExtra("uuid"), 1)
            }, object : BaseAPI<Any>() {
                override fun onSuccess(t: Any?, state: Int, msg: String) {
                    tipSuccess(msg)
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }

            })
        }
        bga_shop_details.setAdapter { _, itemView, model, _ ->
            if (itemView != null && model != null) {
                glideImage(itemView as ImageView, model.toString() ?: "")
            }
        }
        rv_shop_details_details.layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rv_shop_details_details.adapter = imageAdapter

        iv_shop_details_comment.setOnClickListener {
            lifecycleScope.request({
                if (!collection)
                    APIAccount.service().collectionAdd("0", intent.getStringExtra("uuid") ?: "")
                else
                    APIAccount.service().collectionDelete("1", intent.getStringExtra("uuid") ?: "")
            }, object : BaseAPI<Any>() {
                override fun onSuccess(t: Any?, state: Int, msg: String) {
                    tipSuccess(msg)
                    if (!collection) {
                        iv_shop_details_comment.setImageResource(R.drawable.iv_collection_fill)
                    } else {
                        iv_shop_details_comment.setImageResource(R.drawable.iv_collection)
                    }
                    collection = !collection
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }

            })

        }
        tv_shop_details_comment.setOnClickListener {
            lifecycleScope.request({
                if (!collection)
                    APIAccount.service().collectionAdd("0", intent.getStringExtra("uuid") ?: "")
                else
                    APIAccount.service().collectionDelete("1", intent.getStringExtra("uuid") ?: "")
            }, object : BaseAPI<Any>() {
                override fun onSuccess(t: Any?, state: Int, msg: String) {
                    tipSuccess(msg)
                    if (!collection) {
                        iv_shop_details_comment.setImageResource(R.drawable.iv_collection_fill)
                    } else {
                        iv_shop_details_comment.setImageResource(R.drawable.iv_collection)
                    }
                    collection = !collection
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }

            })

        }
        button_shop_details_buy.setOnClickListener {
            startActivity<ConfirmOrderActivity> {
                putExtra("uuid", intent.getStringExtra("uuid"))
                putExtra("type", "ShopDetails")
            }
        }
        getData()
    }

    var collection = false
    private fun getData() {
        showTipLoading()
        lifecycleScope.request({
            APIShop.service().productInfo(intent.getStringExtra("uuid") ?: "")
        }, object : BaseAPI<ShopInfoEntity>() {
            override fun onSuccess(t: ShopInfoEntity?, state: Int, msg: String) {
                hideTipLoading()
                bga_shop_details.setData(t?.product?.product_pic, null)
                tv_shop_details_store_money.text = "￥${t?.product?.max_money}"
                tv_shop_details_now_money.text = "会员价${t?.product?.min_money}元"
                tv_shop_details_name.text = t?.product?.name
                tv_shop_details_kuaidi.text = "快递：" + t?.product?.express
                tv_shop_details_yueshou.text = "月售：" + t?.product?.month_count
                itemAdapter.setNewData(t?.product?.attribute?.split("，"))
                imageAdapter.setNewData(t?.product?.details)
                collection = t?.product?.collection ?: false
                if (t?.product?.collection == true) {
                    iv_shop_details_comment.setImageResource(R.drawable.iv_collection_fill)
                } else {
                    iv_shop_details_comment.setImageResource(R.drawable.iv_collection)
                }
                if (t?.comment.isNullOrEmpty()) {
                    cl_shop_details_comment.gone()
                } else {
                    cl_shop_details_comment.visible()
                    tv_shop_details_mendian.text = "用户评价（${t?.comment_count}）"
                    rv_shop_details_store.layoutManager = object : LinearLayoutManager(context) {
                        override fun canScrollVertically(): Boolean {
                            return false
                        }
                    }
                    rv_shop_details_store.adapter = CommentAdapter().apply {
                        setNewData(t?.comment)
                    }
                }

            }

            override fun onError(e: APIException) {
                hideTipLoading()
                tipFail(e.eMessage)
            }

        })
    }

    class CommentAdapter :
        BaseQuickAdapter<ShopInfoEntity.Comment, BaseViewHolder>(R.layout.item_seller_discuss) {
        override fun convert(helper: BaseViewHolder, item: ShopInfoEntity.Comment?) {
            helper.setText(R.id.tv_name, item?.name)
                .setText(R.id.tv_content, item?.content)
                .setText(R.id.tv_time, item?.time)
            glideImage(
                helper.getView<AppCompatImageView>(R.id.iv_portrait), item?.avatar
                    ?: ""
            )
            val product_star = item?.describes!!.toFloat()
            val server_star = item.logistics!!.toFloat()
            val attitude = item.attitude!!.toFloat()
            val overallStar = ((product_star + server_star + attitude) / 3).toBigDecimal()
                .setScale(1, RoundingMode.HALF_UP).toFloat()
            helper.getView<MaterialRatingBar>(R.id.rating_bar).rating = overallStar
            val recyclerView = helper.getView<RecyclerView>(R.id.recycler_picture_view)
            if (recyclerView.layoutManager == null) {
                recyclerView.layoutManager = object : GridLayoutManager(mContext, 3) {
                    override fun canScrollVertically() = false
                }
            }
            if (item.picture.isNullOrEmpty()) {
                recyclerView.gone()
                recyclerView.adapter = null
            } else {
                recyclerView.visible()
                val adapter = PictureAdapter()
                adapter.bindToRecyclerView(recyclerView)
                adapter.setNewData(item.picture)
            }
        }

        /**
         * 评论图片适配器
         */
        private inner class PictureAdapter :
            BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_seller_discuss_picture) {
            override fun convert(helper: BaseViewHolder, item: String?) {
                val imageView = helper.getView<AppCompatImageView>(R.id.iv_image)
                glideImage(imageView, item ?: "", R.color.colorBack)
            }
        }
    }

    class ImageAdapter : BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_image_view) {
        override fun convert(helper: BaseViewHolder, item: String?) {
            glideImage(helper.getView<ResizableImageView>(R.id.resizable_image_view), item ?: "")
        }

    }

    class DialogAdapter :
        BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_shop_details_coupon) {
        override fun convert(helper: BaseViewHolder, item: String?) {
            val tv_coupon_receive = helper.getView<TextView>(R.id.tv_coupon_receive)
            if (helper.layoutPosition % 2 == 0) {
                tv_coupon_receive.visible()
                helper.setGone(R.id.iv_coupon_receive, false)
            } else {
                tv_coupon_receive.inVisible()
                helper.setGone(R.id.iv_coupon_receive, true)
            }
        }

    }

    class ItemAdapter : BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_main_shop) {
        override fun convert(helper: BaseViewHolder, item: String?) {
            helper.setText(R.id.tv_tab, item)
                .setBackgroundRes(R.id.tv_tab, R.drawable.bg_home_empty_blue)
        }

    }
}